package com.mall.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.mall.common.utils.R;
import com.mall.mall.product.entity.SkuImagesEntity;
import com.mall.mall.product.entity.SpuInfoDescEntity;
import com.mall.mall.product.entity.SpuInfoEntity;
import com.mall.mall.product.feign.SeckillFeignService;
import com.mall.mall.product.service.*;
import com.mall.mall.product.vo.SeckillInfoVO;
import com.mall.mall.product.vo.SkuItemSaleAttrVo;
import com.mall.mall.product.vo.SkuItemVo;
import com.mall.mall.product.vo.SpuItemAttrGroupVo;
import io.netty.util.concurrent.CompleteFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.utils.PageUtils;
import com.mall.common.utils.Query;

import com.mall.mall.product.dao.SkuInfoDao;
import com.mall.mall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SpuInfoService spuInfoService;

    @Autowired
    AttrGroupService attrGroupService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SeckillFeignService seckillFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> warpper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            warpper.and(w->{
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            warpper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            warpper.eq("brand_id", brandId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            warpper.ge("price", min);
        }

        String max = (String) params.get("max");

        if (!StringUtils.isEmpty(max)) {
            try{
                BigDecimal bigDecimal = new BigDecimal(max);
                if (bigDecimal.compareTo(BigDecimal.ZERO) == 1){
                    warpper.le("price", max);
                }
            }catch (Exception e){
                log.error("数据转换错误");
            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                warpper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> spuList = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return spuList;
    }

    @Override
    public SkuItemVo item(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(()->{
            //1、sku 基本信息获取
            SkuInfoEntity info = getById(skuId);
            skuItemVo.setInfo(info);
            Long catalogId = info.getCatalogId();
            Long spuId = info.getSpuId();
            return info;
        }, executor);

        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //3、获取 spu 的销售属性
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        }, executor);

        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            //4、获取 spu 的优惠信息
            SpuInfoDescEntity descEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(descEntity);
        }, executor);

        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //5、获取 spu 的规格参数信息
            List<SpuItemAttrGroupVo> attrs = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrs);
        }, executor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2、sku 的图片信息
            List<SkuImagesEntity> imgs = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(imgs);
        }, executor);

        CompletableFuture<Void> seckillInfoTask = CompletableFuture.runAsync(() -> {
            // 查询当前 sku 是否参会与秒杀优惠
            R response = seckillFeignService.getSkuSeckillInfo(skuId);
            if (0 == response.getCode()) {
                SeckillInfoVO seckillInfoVO = response.getData(new TypeReference<SeckillInfoVO>() {
                });
                skuItemVo.setSeckillSkuVo(seckillInfoVO);
            }
        }, executor);


        try {
            CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imageFuture, seckillInfoTask).get();
        } catch (InterruptedException e) {
            log.error("SkuInfoServiceImpl.item error {}", e);
            e.printStackTrace();
        } catch (ExecutionException e) {
            log.error("SkuInfoServiceImpl.item error {}", e);
            e.printStackTrace();
        }

        return skuItemVo;
    }

}